package cn.schoolwow.util.module.query.reflection.service;

import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.util.module.query.reflection.domain.ReflectionOption;

import java.lang.reflect.Field;

public class GetClassFieldFlow implements BusinessFlow {
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        String fieldName = (String) flowContext.checkData("fieldName");
        ReflectionOption reflectionOption = flowContext.checkInstanceData(ReflectionOption.class);

        Class clazz = reflectionOption.clazz;
        String initialClassName = clazz.getName();
        while(null!=clazz.getSuperclass()){
            try {
                Field field = clazz.getDeclaredField(fieldName);
                field.setAccessible(true);
                flowContext.putReturnData("field", field);
                return;
            } catch (NoSuchFieldException e) {
                clazz = clazz.getSuperclass();
            }
        }
        if(!reflectionOption.ignoreNotExistField){
            throw new IllegalArgumentException("类字段不存在!字段名:"+fieldName+",类名:"+initialClassName);
        }
    }

    public String name() {
        return "获取反射类指定字段";
    }
}
